package top.chengdongqing.portal.user.register;

import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;

import top.chengdongqing.common.constant.UserConstant;
import top.chengdongqing.common.kit.Fail;
import top.chengdongqing.common.model.User;
import top.chengdongqing.portal.user.login.LoginService;

/**
 * 注册相关逻辑层
 * 
 * @author Luyao
 *
 */
public class RegisterService {

	@Inject
	LoginService loginSrv;

	
	public Ret register(
			String phone,
			String password, 
			String ip, 
			boolean sureHasnot) {
		// 判断该手机号是否存在
		if (!sureHasnot && loginSrv.hasAccount(phone)) {
			return Fail.setMsg("该账号已存在，请直接登录");
		}
		// 保存用户信息
		User user = new User();
		user.setPhone(phone);
		user.setSalt(HashKit.generateSaltForSha256());
		user.setPassword(HashKit.sha256(password + user.getSalt()));
		user.setSecurityLevel(User.securityLevel.ORDINARY);
		user.save();
		// 直接登录
		return loginSrv.loginByPhone(phone, ip);
	}
	
	/**
	 * 账号注册
	 * 
	 * @param phone
	 * @param password
	 * @param ip
	 * @param sureHasnot
	 * @return
	 */
	public Ret registerN(
			String username,
			String email,
			String password, 
			String ip, 
			boolean sureHasnot) {
		// 判断该手机号是否存在
		if (!sureHasnot && loginSrv.hasAccount(email)) {
			return Fail.setMsg("The account already exists, please login directly!");
		}
		// 保存用户信息
		User user = new User();
		user.setName(username);
		user.setAvatarUrl(UserConstant.DEFAULT_AVATAR_Url);
		user.setStatus(UserConstant.DEFAULT_ACCOUNT_STATUS);
		user.setPhone(email);
		user.setSalt(HashKit.generateSaltForSha256());
		user.setPassword(HashKit.sha256(password + user.getSalt()));
		user.setSecurityLevel(User.securityLevel.ORDINARY);
		user.save();
		// 直接登录
		return loginSrv.loginByPhone(email, ip);
	}
	
	
}
